package com.engine.jyc.controller;

import com.engine.kq.biz.KQLeaveRulesComInfo;
import com.engine.kq.biz.KQOvertimeRulesBiz;
import com.engine.kq.biz.KQUnitBiz;
import com.engine.kq.enums.KqSplitFlowTypeEnum;
import com.engine.kq.util.KQDurationCalculatorUtil;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.systeminfo.SystemEnv;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2024/11/29
 * @Description 绩效
 * @Author AdminZm
 */
public class JxController {

    BaseBean baseBean = new BaseBean();

    @GET
    @Path("/getJxInfo")
    @Produces(MediaType.APPLICATION_JSON)
    public String getJxInfo(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                @QueryParam("id") String id, @QueryParam("type") String type, @QueryParam("ny") String ny) {
        Map<String, Object> resultMap = new HashMap<>();
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        baseBean.writeLog("getJxInfo start:" + id + "、" + type + "、" + ny);
        try {
            if (StringUtils.isEmpty(id) || StringUtils.isEmpty(type) || StringUtils.isEmpty(ny)) {
                return new Gson().toJson(resultMap);
            }
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            // 解析字符串为YearMonth对象
            YearMonth yearMonth = YearMonth.parse(ny, formatter);
            // 本月最后一天
            LocalDate lastDay = yearMonth.atEndOfMonth();
            // 本月第一天
            LocalDate firstDay = yearMonth.atDay(1);
            // 获取上个月的YearMonth对象
            YearMonth previousYearMonth = yearMonth.minusMonths(1);
            String previousStr = previousYearMonth.format(formatter);
            KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
            KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz();
            int uintType = kqOvertimeRulesBiz.getMinimumUnit();//当前加班单位
            double hoursToDay = kqOvertimeRulesBiz.getHoursToDay();//当前天跟小时计算关系
            Map<String, Object> resultMapA = new HashMap<>();
            if (StringUtils.equals(type, "hrm")) {
                // 获取上月绩效
                String syjx = "0";
                rs.executeQuery("SELECT jxje FROM uf_ydbmjxtb WHERE xm = ? AND jjyf = ?", id, previousStr);
                if (rs.next()) {
                    syjx = rs.getString("jxje");
                }
                String cqts = "0";
                // 获取实际出勤
                // 获取实际出勤
                rs.execute("SELECT sum(attendancedays) AS attendancedays FROM kq_format_total WHERE resourceid = " + id +
                        " AND kqdate >='" + firstDay + "' and kqdate <= '" + lastDay + "'");
                if (rs.next()) {
                    cqts = rs.getString("attendancedays");
                }
                String sql = " select b.resourceid, b.newleavetype, b.durationrule, sum(b.duration) as val, c.leaveName, " +
                        "c.minimumUnit from "
                        + KqSplitFlowTypeEnum.LEAVE.getTablename()+" b, KQ_LeaveRules c "+
                        " where b.newleavetype = c.id and b.belongdate >='"+firstDay+"' and b.belongdate <='"+lastDay+"' and b.resourceid = " +
                        id + " group by b.resourceid, b.newleavetype, b.durationrule, c.leaveName, c.minimumUnit ";
                String qjxx = "";
                rs.execute(sql);
                while (rs.next()) {
                    String resourceid = rs.getString("resourceid");
                    String newleavetype = rs.getString("newleavetype");
                    String durationrule = rs.getString("durationrule");
                    String leaveName = rs.getString("leaveName");
                    String minimumUnit = rs.getString("minimumUnit");
                    double value = rs.getDouble("val")<0?0:rs.getDouble("val");

                    double proportion = Util.getDoubleValue(kqLeaveRulesComInfo.getProportion(newleavetype));
                    if(KQUnitBiz.isLeaveHour(newleavetype, kqLeaveRulesComInfo)){//按小时
                        if(!KQUnitBiz.isLeaveHour(durationrule)){
                            if(proportion>0) {
                                value = value*proportion;
                            }
                        }
                    }else{//按天
                        if(KQUnitBiz.isLeaveHour(durationrule)){
                            if(proportion>0) value = value/proportion;
                        }
                    }

                    String unitTypeName = null;
                    String unitType = "1";
                    if (StringUtils.equals(minimumUnit, "3")) {
                        unitType = "2";
                    }
                    if(Util.null2String(unitType).length()>0){
                        if(unitType.equals("1")){
                            unitTypeName= SystemEnv.getHtmlLabelName(1925, 7);
                        }else if(unitType.equals("2")){
                            unitTypeName=SystemEnv.getHtmlLabelName(391, 7);
                        }else if(unitType.equals("3")){
                            unitTypeName=SystemEnv.getHtmlLabelName(18083, 7);
                        }
                    }

                    qjxx = qjxx + leaveName + ":" + value + unitTypeName + "\n";
                }

                sql = " select resourceid,changeType, sum(cast(duration_min as decimal(18,4))) as val,paidLeaveEnable "+
                        " from hrmresource a, kq_flow_overtime b "+
                        " where a.id = b.resourceid and belongdate >='"+firstDay+"' and belongdate <='"+lastDay+"' and b.resourceid = "
                        + id + " group by resourceid,changeType,paidLeaveEnable  ";
                String gzrjb = "0";
                String xxrjb = "0";
                rs.execute(sql);
                while (rs.next()) {
                    String resourceid = rs.getString("resourceid");
                    String paidLeaveEnable = rs.getString("paidLeaveEnable");
                    int changeType = rs.getInt("changeType");//1-节假日、2-工作日、3-休息日
                    double value = rs.getDouble("val") < 0 ? 0 : rs.getDouble("val");
                    if (uintType == 3 || uintType == 5 || uintType == 6) {//按小时计算
                        value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value / (60.0) + ""));
                    } else {//按天计算
                        value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value / (60.0 * hoursToDay) + ""));
                    }

                    if (changeType == 1) {

                    } else if (changeType == 2) {
                        gzrjb = new BigDecimal(gzrjb).add(new BigDecimal(String.valueOf(value))).toString();
                    } else if (changeType == 3) {
                        xxrjb = new BigDecimal(xxrjb).add(new BigDecimal(String.valueOf(value))).toString();
                    }
                }
                String jbxx = "";
                if (StringUtils.isNotEmpty(gzrjb) && new BigDecimal(gzrjb).compareTo(BigDecimal.ZERO) > 0) {
                    jbxx = jbxx + "工作日加班:" + gzrjb + "小时\n";
                }
                if (StringUtils.isNotEmpty(xxrjb) && new BigDecimal(xxrjb).compareTo(BigDecimal.ZERO) > 0) {
                    jbxx = jbxx + "休息日加班:" + xxrjb + "小时";
                }

                String jcxx = "";
                rs.execute("SELECT * FROM uf_jycjcxx WHERE xm = " + id + " AND jfrq >= '" + firstDay
                        + "' AND jfrq <= '" + lastDay +"'");
                while (rs.next()) {
                    String jfrq = rs.getString("jfrq");
                    String jflb = rs.getString("jflb");
                    String jfje = rs.getString("jfje");

                    if (StringUtils.isEmpty(jfrq) || StringUtils.isEmpty(jflb)) {
                        continue;
                    }
                    String jflbStr = getSelectNameMain("jflb", "-43", jflb);
                    jcxx = jcxx + jfrq + " " + jflbStr + " " + jfje + "\n";
                }

                String cdztxx = "";
                rs.execute("select sum(beLate) as beLate,sum(graveBeLate) as graveBeLate,sum(leaveEearly) as leaveEearly," +
                        " sum(graveLeaveEarly) as graveLeaveEarly from kq_format_total WHERE resourceid = " + id +
                        " and kqdate >='"+firstDay+"' and kqdate <='"+lastDay+"'");
                while (rs.next()) {
                    String beLate = rs.getString("beLate");
                    String graveBeLate = rs.getString("graveBeLate");
                    String leaveEearly = rs.getString("leaveEearly");
                    String graveLeaveEarly = rs.getString("graveLeaveEarly");

                    if (StringUtils.isNotEmpty(beLate)) {
                        cdztxx = cdztxx + "迟到:" + beLate + "次" + "\n";
                    }
                    if (StringUtils.isNotEmpty(graveBeLate)) {
                        cdztxx = cdztxx + "严重迟到:" + graveBeLate + "次" + "\n";
                    }
                    if (StringUtils.isNotEmpty(leaveEearly)) {
                        cdztxx = cdztxx + "早退:" + beLate + "次" + "\n";
                    }
                    if (StringUtils.isNotEmpty(graveLeaveEarly)) {
                        cdztxx = cdztxx + "严重早退:" + graveLeaveEarly + "次" + "\n";
                    }
                }

                Map<String, String> mapTemp = new HashMap<>();
                mapTemp.put("syjx", syjx);
                mapTemp.put("cqts", cqts);
                mapTemp.put("qjxx", qjxx);
                mapTemp.put("jbxx", jbxx);
                mapTemp.put("jcxx", jcxx);
                mapTemp.put("cdztxx", cdztxx);
                resultMapA.put(id, mapTemp);
            } else {
                String[] idArr = id.split(",");
                for (String idT : idArr) {
                    // 获取上月绩效
                    String syjx = "0";
                    rs.executeQuery("SELECT jxje FROM uf_ydbmjxtb WHERE xm = ? AND jjyf = ?", idT, previousStr);
                    if (rs.next()) {
                        syjx = rs.getString("jxje");
                    }
                    String cqts = "0";
                    // 获取实际出勤
                    rs.execute("SELECT sum(attendancedays) AS attendancedays FROM kq_format_total WHERE resourceid = " + idT +
                            " AND kqdate >='" + firstDay + "' and kqdate <= '" + lastDay + "'");
                    if (rs.next()) {
                        cqts = rs.getString("attendancedays");
                    }
                    String sql = " select b.resourceid, b.newleavetype, b.durationrule, sum(b.duration) as val, c.leaveName, " +
                            "c.minimumUnit from "
                            + KqSplitFlowTypeEnum.LEAVE.getTablename()+" b, KQ_LeaveRules c "+
                            " where b.newleavetype = c.id and b.belongdate >='"+firstDay+"' and b.belongdate <='"+lastDay+"' and b.resourceid = " +
                            idT + " group by b.resourceid, b.newleavetype, b.durationrule, c.leaveName, c.minimumUnit ";
                    String qjxx = "";
                    rs.execute(sql);
                    while (rs.next()) {
                        String resourceid = rs.getString("resourceid");
                        String newleavetype = rs.getString("newleavetype");
                        String durationrule = rs.getString("durationrule");
                        String leaveName = rs.getString("leaveName");
                        String minimumUnit = rs.getString("minimumUnit");
                        double value = rs.getDouble("val")<0?0:rs.getDouble("val");

                        double proportion = Util.getDoubleValue(kqLeaveRulesComInfo.getProportion(newleavetype));
                        if(KQUnitBiz.isLeaveHour(newleavetype, kqLeaveRulesComInfo)){//按小时
                            if(!KQUnitBiz.isLeaveHour(durationrule)){
                                if(proportion>0) {
                                    value = value*proportion;
                                }
                            }
                        }else{//按天
                            if(KQUnitBiz.isLeaveHour(durationrule)){
                                if(proportion>0) value = value/proportion;
                            }
                        }

                        String unitTypeName = null;
                        String unitType = "1";
                        if (StringUtils.equals(minimumUnit, "3")) {
                            unitType = "2";
                        }
                        if(Util.null2String(unitType).length()>0){
                            if(unitType.equals("1")){
                                unitTypeName= SystemEnv.getHtmlLabelName(1925, 7);
                            }else if(unitType.equals("2")){
                                unitTypeName=SystemEnv.getHtmlLabelName(391, 7);
                            }else if(unitType.equals("3")){
                                unitTypeName=SystemEnv.getHtmlLabelName(18083, 7);
                            }
                        }

                        qjxx = qjxx + leaveName + ":" + value + unitTypeName + "\n";
                    }

                    sql = " select resourceid,changeType, sum(cast(duration_min as decimal(18,4))) as val,paidLeaveEnable "+
                            " from hrmresource a, kq_flow_overtime b "+
                            " where a.id = b.resourceid and belongdate >='"+firstDay+"' and belongdate <='"+lastDay+"' and b.resourceid = "
                            + idT + " group by resourceid,changeType,paidLeaveEnable  ";
                    String gzrjb = "0";
                    String xxrjb = "0";
                    rs.execute(sql);
                    while (rs.next()) {
                        String resourceid = rs.getString("resourceid");
                        String paidLeaveEnable = rs.getString("paidLeaveEnable");
                        int changeType = rs.getInt("changeType");//1-节假日、2-工作日、3-休息日
                        double value = rs.getDouble("val") < 0 ? 0 : rs.getDouble("val");
                        if (uintType == 3 || uintType == 5 || uintType == 6) {//按小时计算
                            value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value / (60.0) + ""));
                        } else {//按天计算
                            value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value / (60.0 * hoursToDay) + ""));
                        }

                        if (changeType == 1) {

                        } else if (changeType == 2) {
                            gzrjb = new BigDecimal(gzrjb).add(new BigDecimal(String.valueOf(value))).toString();
                        } else if (changeType == 3) {
                            xxrjb = new BigDecimal(xxrjb).add(new BigDecimal(String.valueOf(value))).toString();
                        }
                    }
                    String jbxx = "";
                    if (StringUtils.isNotEmpty(gzrjb) && new BigDecimal(gzrjb).compareTo(BigDecimal.ZERO) > 0) {
                        jbxx = jbxx + "工作日加班:" + gzrjb + "小时\n";
                    }
                    if (StringUtils.isNotEmpty(xxrjb) && new BigDecimal(xxrjb).compareTo(BigDecimal.ZERO) > 0) {
                        jbxx = jbxx + "休息日加班:" + xxrjb + "小时";
                    }

                    String jcxx = "";
                    rs.execute("SELECT * FROM uf_jycjcxx WHERE xm = " + idT + " AND jfrq >= '" + firstDay
                            + "' AND jfrq <= '" + lastDay +"'");
                    while (rs.next()) {
                        String jfrq = rs.getString("jfrq");
                        String jflb = rs.getString("jflb");
                        String jfje = rs.getString("jfje");

                        if (StringUtils.isEmpty(jfrq) || StringUtils.isEmpty(jflb)) {
                            continue;
                        }
                        String jflbStr = getSelectNameMain("jflb", "-43", jflb);
                        jcxx = jcxx + jfrq + " " + jflbStr + " " + jfje + "\n";
                    }

                    String cdztxx = "";
                    rs.execute("select sum(beLate) as beLate,sum(graveBeLate) as graveBeLate,sum(leaveEearly) as leaveEearly," +
                            " sum(graveLeaveEarly) as graveLeaveEarly from kq_format_total WHERE resourceid = " + idT +
                            " and kqdate >='"+firstDay+"' and kqdate <='"+lastDay+"'");
                    while (rs.next()) {
                        String beLate = rs.getString("beLate");
                        String graveBeLate = rs.getString("graveBeLate");
                        String leaveEearly = rs.getString("leaveEearly");
                        String graveLeaveEarly = rs.getString("graveLeaveEarly");

                        if (StringUtils.isNotEmpty(beLate) && new BigDecimal(beLate).compareTo(BigDecimal.ZERO) > 0) {
                            cdztxx = cdztxx + "迟到:" + beLate + "次" + "\n";
                        }
                        if (StringUtils.isNotEmpty(graveBeLate) && new BigDecimal(graveBeLate).compareTo(BigDecimal.ZERO) > 0) {
                            cdztxx = cdztxx + "严重迟到:" + graveBeLate + "次" + "\n";
                        }
                        if (StringUtils.isNotEmpty(leaveEearly) && new BigDecimal(leaveEearly).compareTo(BigDecimal.ZERO) > 0) {
                            cdztxx = cdztxx + "早退:" + beLate + "次" + "\n";
                        }
                        if (StringUtils.isNotEmpty(graveLeaveEarly) && new BigDecimal(graveLeaveEarly).compareTo(BigDecimal.ZERO) > 0) {
                            cdztxx = cdztxx + "严重早退:" + graveLeaveEarly + "次" + "\n";
                        }
                    }

                    Map<String, String> mapTemp = new HashMap<>();
                    mapTemp.put("syjx", syjx);
                    mapTemp.put("cqts", cqts);
                    mapTemp.put("qjxx", qjxx);
                    mapTemp.put("jbxx", jbxx);
                    mapTemp.put("jcxx", jcxx);
                    mapTemp.put("cdztxx", cdztxx);
                    resultMapA.put(idT, mapTemp);
                }
            }

            resultMap.put("code", "200");
            resultMap.put("data", resultMapA);
        } catch (Exception e) {
            resultMap.put("code", "500");
            baseBean.writeLog("getJxInfo error:" + e);
        }
        return new Gson().toJson(resultMap);
    }

    private String getSelectNameMain(String fieldName, String billid, String selectValue) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from workflow_billfield where fieldname = ? and billid = ? and viewtype=0", fieldName, billid);
        rs.next();
        int fieldId = com.weaver.general.Util.getIntValue(rs.getString("id"),-1);
        rs.executeQuery("select selectname from workflow_SelectItem where fieldid = ? and selectvalue = ?", fieldId, selectValue);
        rs.next();
        return com.weaver.general.Util.null2String(rs.getString("selectname"));
    }
}
